import os
import sys
import csv
import itertools

from PyQt5 import QtCore
from collections import OrderedDict

from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtWidgets import QAction
from PyQt5.QtWidgets import qApp
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QVBoxLayout
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtWidgets import QWidget
from PyQt5.QtWidgets import QGridLayout
from PyQt5.QtWidgets import QHBoxLayout
from PyQt5.QtWidgets import QLineEdit
from PyQt5.QtWidgets import QTabWidget
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QFrame
from PyQt5.QtWidgets import QColorDialog
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QCheckBox
from PyQt5.QtWidgets import QScrollArea
from PyQt5.QtWidgets import QTextEdit
from PyQt5.QtWidgets import QLabel

from PyQt5.QtGui import QIcon
from PyQt5.QtGui import QColor
from PyQt5.QtGui import QDrag
from PyQt5.QtGui import QTextCursor
from PyQt5.QtGui import QPixmap

from PyQt5.QtCore import Qt
from PyQt5.QtCore import QObject
from PyQt5.QtCore import QMimeData
from PyQt5.QtCore import pyqtSignal

csv.register_dialect('mydialect', delimiter='\t', quoting=csv.QUOTE_MINIMAL)


class Store(object):
    def __init__(self):
        img_file_list = []
        self.song_g = OrderedDict()
        img_path = 'discimg'
        for _, _, t in os.walk(img_path):
            img_file_list = t[:]

        with open('songlist.csv', 'r', encoding='utf-16') as f:
            self.song_list = []
            for r in csv.DictReader(f, dialect='mydialect'):
                for img_name in img_file_list:
                    if ('%s_' % r['name']) in img_name or img_name.startswith(r['name']):
                        r['discimg'] = '%s/%s' % (img_path, img_name)
                self.song_list.append(r)

        self.fieldnames = [_ for _ in self.song_list[0].keys() if _ not in ['discimg']]

    def g_song_csv(self):
        import shutil
        try:
            if not os.path.exists('Resource'):
                os.mkdir('Resource')
            if not os.path.exists('Resource/DiscInfo'):
                os.mkdir('Resource/DiscInfo')
        except WindowsError:
            pass
        try:
            temp_songlist = OrderedDict()
            with open('Resource/DiscInfo/discstock.csv', 'w', newline='', encoding='UTF-16') as _:
                writer = csv.DictWriter(_, fieldnames=self.fieldnames, dialect='mydialect')
                writer.writeheader()
                for index, (k, v) in enumerate(self.song_g.items()):
                    print(index, k, v)
                    v['no'] = index + 1
                    row = {tk: '"%s"' % tv if isinstance(tv, str) and tv.find(',') != -1 else tv for tk, tv in v.items() if
                           tk not in ['discimg']}
                    temp_songlist[row['no']] = row
                    print(row)
                    writer.writerow(row)

            fieldnames_pop = [
                'stage1',
                'songname',
                'SP',
                'PT',
                'Hid',
                'SP',
                'PT',
                'Hid',
                'SP',
                'PT',
                'Hid',
                'SP',
                'PT',
                'Hid'
            ]
            for file_i in range(1, 4):
                with open('Resource/DiscInfo/pop_stage_%d.csv' % file_i, 'w', newline='', encoding='UTF-8') as f:
                    f.write('%s\n' % ','.join(fieldnames_pop))
                    for index, (k, v) in enumerate(temp_songlist.items()):
                        f.write('%s\n' % ','.join(map(lambda x: str(x), [
                            v['no'],  # stage1
                            v['name'],  # songname
                            2,  # SP
                            1 if int(v['Pop_1']) else 0,  # PT
                            0,  # Hid
                            2,  # SP
                            2 if int(v['Pop_2']) else 0,  # PT
                            0,  # Hid
                            2,  # SP
                            3 if int(v['Pop_3']) else 0,  # PT
                            0,  # Hid
                            2,  # SP
                            4 if int(v['Pop_4']) else 0,  # PT
                            0,  # Hid
                        ])))
                        print(index, k, v)
            print('suc g')
        except:
            import traceback
            traceback.print_exc()


store = Store()

def main1():
    app = QApplication(sys.argv)
    win = QMainWindow()
    from technikasonglisteditor import Ui_MainWindow
    ui = Ui_MainWindow()
    ui.setupUi(win)
    win.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main1()
